package com.netcracker.training.automonic.parser;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.netcracker.training.automonic.dao.factories.DAOFactory;

/**
 * Parent of parsers,that use <a href="http://jsoup.org/">JSoup</a> library
 * 
 * @author lester
 * 
 */
public abstract class JsoupParser {

	private static final Logger log = Logger.getLogger(JsoupParser.class);
	protected Document doc;
	protected DAOFactory daoFactory;

	/**
	 * Returns the next page(HTML Document) if it exist,else returns null
	 * 
	 * @param cssQuery
	 *            CSS syntax query to next link
	 * @param homePage
	 *            index page of web-site
	 * @return HTML Document of next page
	 */
	protected Document getNextPage(String cssQuery, String homePage) {
		String nextLink;
		Elements nextButton = doc.select(cssQuery);
		if (nextButton.first() != null) {
			nextLink = nextButton.first().attr("href");
		} else
			return null;
		doc = getDocumentByConnect(homePage + nextLink);
		return doc;
	}

	/**
	 * Get HTML Document by the specified {@link #URL} address
	 * 
	 * @return parsed Document
	 */
	protected Document getDocumentByConnect(String URL) {
		try {
			doc = Jsoup.connect(URL).get();
			return doc;
		} catch (IOException e) {
			log.trace("Error when connect", e);
			return null;
		}
	}
}
